﻿using ICSharpCode.SharpZipLib.GZip;
using Lg.Core.Exceptions;
using Microsoft.AspNetCore.Http;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Lg.Core.FileHelper
{
    public class Base
    {
        /// <summary>
        /// 上传文件大小,单位MB
        /// </summary>
        private long? _size;
        /// <summary>
        /// 相对地址
        /// </summary>
        private string? _path;
        /// <summary>
        /// 允许的扩展名
        /// </summary>
        private List<string>? _allowFileType;
        /// <summary>
        /// 上传的文件对象
        /// </summary>
        private IFormFile _file;

        public string ExtendName { get; }

        public Base(long size, string path, List<string> allowFileType, IFormFile fileObj)
        {
            if (size <= 0)
            {
                throw new Exception("上传文件大小参数不正确");
            }
            if (string.IsNullOrEmpty(path))
            {
                throw new Exception("上传文件地址参数不正确");
            }
            if (allowFileType == null || !allowFileType.Any())
            {
                allowFileType = new List<string>()
                { ".jpg", ".jpeg", ".png", ".gif", ".doc",".docx",".xls", ".xlsx", ".ppt", ".pdf", ".txt", ".zip", ".rar", ".mp4", ".mp3", ".flv" };
            }
            _size = size;
            _path = path;
            _allowFileType = allowFileType;
            _file = fileObj ?? throw new Exception("上传文件不正确");
            {
                var index = _file.FileName.LastIndexOf('.');
                this.ExtendName = _file.FileName.Substring(index).ToLower();
            }
        }

        public Base(IFormFile file,string allowFileType,long limitSize,string path="/uploads/")
        {
            this._file = file;
            this._path = path;
            this._allowFileType = allowFileType.Split(",").Select(x =>
            {
                return x.StartsWith(".") ? x : $".{x}";
            }).ToList();
            this._size = limitSize;
            {
                var index = _file.FileName.LastIndexOf('.');
                this.ExtendName = _file.FileName.Substring(index).ToLower();
            }
        }

        public string Up()
        {
            var index = _file.FileName.LastIndexOf('.');
            var extenName = _file.FileName.Substring(index).ToLower();
            var fileName = Lg.Core.Random.NewRandom(5);
            var fullFileName = fileName + extenName;
            var fullPath = (AppContext.BaseDirectory + _path).Replace("/", "\\");
            if (!_allowFileType.Contains(extenName))
            {
                throw new Exception($"上传文件扩展名[.{extenName}]不在允许范围内");
            }
            if (_file.Length > _size * 1048576)
            {
                throw new Exception($"上传文件大小不能超过{_size}MB");
            }
            if (!Directory.Exists(fullPath))
            {
                Directory.CreateDirectory(fullPath);
            }

            using (var stream = new System.IO.FileStream(fullPath + fullFileName, FileMode.Create))
            {
                byte[] fileHeader = new byte[2];
                var fileStream = _file.OpenReadStream();
                //fileStream.Read(fileHeader, 0, 2);
                //string fileHeaderStr = "";
                //foreach (var item in fileHeader)
                //{
                //    fileHeaderStr += item.ToString();
                //}
                //this.FileExtensions.TryGetValue(fileHeaderStr, out string? allowExtenName);
                //if (allowExtenName == null)
                //{
                //    throw new Exception("上传文件不在允许范围内");
                //}
                //if (!allowExtenName.Split(',').Contains(extenName.TrimStart('.')))
                //{
                //    throw new Exception("上传文件不在允许范围内");
                //}
                _file.CopyTo(stream);
            }

            return _path + fullFileName;
        }
        public Dictionary<string, string> FileExtensions = new Dictionary<string, string>
        {
               {"255216","jpg,jpeg"},
               { "7173", "gif"},
               { "6677", "bmp" },
               { "13780", "png" },
               { "7790", "com,exe,dll" },
               { "8297", "rar" },
               { "8075", "zip,xls,docx,xlsx" },
               { "6063", "xml,html" },
               { "239187", "aspx" },
               { "117115", "cs" },
               { "119105", "js" },
               { "210187", "txt" },
               { "64101", "bat" },
               { "10056", "btseed" },
               { "255254", "rdp" },
               { "5666", "psd" },
               { "3780", "pdf" },
               { "7384", "chm" },
               { "70105", "log" },
               { "8269", "reg" },
               { "6395", "hlp" },
               { "208207", "doc,xls,docx,xlsx" },
               { "00", "mp4" }

        };
        public byte[] Down()
        {
            var fullPath = (AppContext.BaseDirectory + _path).Replace("/", "\\");

            return System.IO.File.ReadAllBytes(fullPath);
        }
        /// <summary>
        /// 较验文件类型和文件尺寸
        /// </summary>
        /// <exception cref="LgException"></exception>
        public void Valide()
        {
            if(this._size!=null&& _file.Length > _size * 1048576)
            {
                throw new LgException($"上传文件大小不能超过{_size}M");
            }
            if (this._allowFileType != null && this._allowFileType.Count > 0)
            {
                var index = _file.FileName.LastIndexOf('.');
                var extenName = _file.FileName.Substring(index).ToLower();
                if (!_allowFileType.Contains(extenName))
                {
                    throw new LgException($"上传文件类型[{extenName}]不在允许范围内！");
                }
                //byte[] fileHeader = new byte[4];
                //using var fileStream = _file.OpenReadStream();
                //fileStream.Read(fileHeader, 0, 4);
                //string fileHeaderStr = "";
                //foreach (var item in fileHeader)
                //{
                //    fileHeaderStr += item.ToString();
                //}
                //this.FileExtensions.TryGetValue(fileHeaderStr, out string? allowExtenName);
                //if (allowExtenName == null||!allowExtenName.Split(',').Contains(extenName.TrimStart('.')))
                //{
                //    throw new LgException("FileCode is not defined !");
                //}
            } 
        }
    }
}
